<!--
  @author:  long
  @date:    2023/3/29
  @file:    xx
  @require:
-->
<template>
  <div class="monthSetUp">
    <el-form>
      <el-row>
        <el-col :span="24">
          <el-form-item label="年度">
            <div class="flex items-center justify-between w-full">
              <el-date-picker
                v-model="form.year"
                type="year"
                placeholder="请选择年份"
                :disabled-date="setYearDisabledDate"
                value-format="YYYY"
                format="YYYY"
                @change="selectChange"
              />
              <el-button @click="handleSave" type="primary">保存</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-for="(item, index) in formItems" :key="index">
          <el-form-item :label="item.label">
            <div :gutter="10" class="flex items-center justify-between w-full">
              <el-date-picker
                v-model="form[item.prop]"
                type="daterange"
                style="width: 100%"
                class="mr-2"
                ref="formDetaRef"
                value-format="YYYY-MM-DD"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                :default-value="item.defaultValue"
                :disabled-date="
                  time => {
                    return setDisabledDate(time, index)
                  }
                "
              />
              <el-input
                v-model="form[item.prop1]"
                placeholder="备注"
              ></el-input>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup name="MonthSetUp">
import { getCurrentInstance } from 'vue'
import { format, startOfMonth, endOfMonth } from 'date-fns'
import {
  getScheduleInfo,
  saveScheduleInfo
} from '@/api/officeManage/evaluation'
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const props = defineProps({
  year: {
    type: String,
    default: ''
  }
})

const data = reactive({
  form: {
    year: format(new Date(), 'yyyy'),
    janTime: '',
    janRemark: '',
    febTime: '',
    febRemark: '',
    marTime: '',
    marRemark: '',
    aprTime: '',
    aprRemark: '',
    mayTime: '',
    mayRemark: '',
    junTime: '',
    junRemark: '',
    julTime: '',
    julRemark: '',
    augTime: '',
    augRemark: '',
    septTime: '',
    septRemark: '',
    octTime: '',
    octRemark: '',
    novTime: '',
    novRemark: '',
    decTime: '',
    decRemark: ''
  },
  formItems: [
    // 一月到十二月
    {
      label: '一月',
      prop: 'janTime',
      prop1: 'janRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '二月',
      prop: 'febTime',
      prop1: 'febRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '三月',
      prop: 'marTime',
      prop1: 'marRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '四月',
      prop: 'aprTime',
      prop1: 'aprRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '五月',
      prop: 'mayTime',
      prop1: 'mayRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '六月',
      prop: 'junTime',
      prop1: 'junRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '七月',
      prop: 'julTime',
      prop1: 'julRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '八月',
      prop: 'augTime',
      prop1: 'augRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '九月',
      prop: 'septTime',
      prop1: 'septRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '十月',
      prop: 'octTime',
      prop1: 'octRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '十一月',
      prop: 'novTime',
      prop1: 'novRemark',
      defaultValue: [],
      id: ''
    },
    {
      label: '十二月',
      prop: 'decTime',
      prop1: 'decRemark',
      defaultValue: [],
      id: ''
    }
  ]
})
const { form, formItems } = toRefs(data)
const emits = defineEmits(['closeDrawer'])

/**
 *设置form表单数据显示
 */
const setInfoData = (data, year = format(new Date(), 'yyyy')) => {
  if (data.length > 0) {
    data.forEach((item, index) => {
      form.value[formItems.value[index].prop] = [
        item.assessStime,
        item.assessEtime
      ]
      form.value[formItems.value[index].prop1] = item.assessRemark
      formItems.value[index].id = item.id
    })
  } else {
    form.value = {
      year: year,
      janTime: '',
      janRemark: '',
      febTime: '',
      febRemark: '',
      marTime: '',
      marRemark: '',
      aprTime: '',
      aprRemark: '',
      mayTime: '',
      mayRemark: '',
      junTime: '',
      junRemark: '',
      julTime: '',
      julRemark: '',
      augTime: '',
      augRemark: '',
      septTime: '',
      septRemark: '',
      octTime: '',
      octRemark: '',
      novTime: '',
      novRemark: '',
      decTime: '',
      decRemark: ''
    }
    formItems.value.forEach(item => {
      item.id = ''
    })
  }
}

/**
 * @description: 保存
 */
const handleSave = () => {
  let params = []
  console.info('form.value', form.value)
  formItems.value.forEach((item, index) => {
    let obj = {
      orgId: userStore.user.orgId,
      deptId: userStore.user.deptId,
      assessAtYear: form.value.year,
      assessStime: '',
      assessEtime: '',
      assessStatus: '0', //0考评期未开始 1考评期进行中 2考评期已结束
      assessRemark: form.value[item.prop1],
      assessAtTime: index + 1,
      resultInMonth: index < 9 ? '0' + (index + 1) : index + 1 + '',
      scheduleType: '0',
      id: item.id
    }
    if (form.value[item.prop] != null && form.value[item.prop].length > 0) {
      obj.assessStime =
        form.value[item.prop][0] != null
          ? form.value[item.prop][0] + ' 00:00:00'
          : ''
      obj.assessEtime =
        form.value[item.prop][1] != null
          ? form.value[item.prop][1] + ' 23:59:59'
          : ''
    }
    params.push(obj)
  })

  //   保存考评日历
  saveScheduleInfo(params).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(res.msg)
      emits('closeDrawer', form.value.year)
    }
  })
}

/**
 * 设置年份禁用日期
 */
const setYearDisabledDate = (time, index) => {
  let year = format(new Date(), 'yyyy') * 1
  let pre = new Date(year - 5 + '-01-01')
  let nex = new Date(year + 5 + '-12-31')
  return time < pre || time > nex
}

/**
 * @description: 设置禁用日期
 *
 */
const setDisabledDate = (time, index) => {
  // return (
  //   time.getTime() < formItems.value[index].defaultValue[0].getTime() ||
  //   time.getTime() > formItems.value[index].defaultValue[1].getTime()
  // )
}

/**
 * @description: 年份改变111
 */
const selectChange = () => {
  setDefaultTime()
  handleCalendarQuery()
}

/**
 * 设置默认时间
 */
const setDefaultTime = () => {
  formItems.value.forEach((item, index) => {
    let v = `${form.value.year}-${index + 1}`
    let c = new Date(v)
    item.defaultValue = [startOfMonth(c), endOfMonth(c)]
  })
  console.info('formItems.value', formItems.value)
}

/**
 * @description: 查询考评日历（季度）
 */
const handleCalendarQuery = () => {
  let params = {
    orgId: userStore.user.orgId,
    deptId: userStore.user.deptId,
    scheduleType: '0',
    assessAtYear: form.value.year
  }

  getScheduleInfo(params).then(res => {
    let data =
      res.data == null || res.data.length == 0
        ? []
        : res.data.sort((ar1, ar2) => ar1.assessAtTime - ar2.assessAtTime)
    setInfoData(data, form.value.year)
  })
}

/**
 * 初始化
 */
const init = async () => {
  setDefaultTime()
  //   设置年份
  form.value.year = props.year
  //   查询考评日历
  await handleCalendarQuery()
}
init()
</script>

<style scoped lang="scss"></style>
